﻿@inherits BaseAfterRenderComponent
@typeparam TItem
@typeparam TValue
<Dropdown ElementId="@ElementId" Class="@DropdownClassNames" Style="@CssStyle" Attributes="@Attributes" Visible="@(DropdownVisible || NotFoundVisible)">
    <Validation Validator="@(Validator ?? ValidationRule.None)">
        <TextEdit @ref="@textEditRef"
                  Role="TextRole.Search"
                  Text="@SelectedText"
                  TextChanged="@OnTextChangedHandler"
                  Placeholder="@Placeholder"
                  Size="@Size"
                  Disabled="@Disabled"
                  TabIndex="@TabIndex"
                  KeyDown="@OnTextKeyDownHandler"
                  FocusIn="@OnTextFocusInHandler"
                  Blur="@OnTextBlurHandler"
                  ChangeTextOnKeyPress="@ChangeTextOnKeyPress"
                  DelayTextOnKeyPress="@DelayTextOnKeyPress"
                  DelayTextOnKeyPressInterval="@DelayTextOnKeyPressInterval"
                  CustomValidationValue="@(( ) => FreeTyping ? SelectedText?.ToString() : SelectedValue?.ToString())">
            <Feedback>
                <ValidationError />
                <ValidationSuccess />
                <ValidationNone />
            </Feedback>
        </TextEdit>
    </Validation>
    <DropdownMenu>
        @if ( NotFoundVisible )
        {
            <DropdownItem Disabled="true">
                @NotFoundContent( SelectedText )
            </DropdownItem>
        }

        @if ( DropdownVisible )
        {
            // once the menu is opened we need to register it as closable so that user could properly close it with escape key
            // without accidentally triggering the parent component closing
            if ( !jsRegistered )
            {
                jsRegistered = true;

                ExecuteAfterRender( async () =>
                {

                    await JSRunner.RegisterClosableComponent( dotNetObjectRef, ElementRef );
                } );
            }

            for ( int i = 0; i < FilteredData.Count; ++i )
            {
                var item = FilteredData[i];

                var text = TextField?.Invoke( item );
                var value = ValueField != null ? ValueField.Invoke( item ) : default;

                <DropdownItem Active="@(i == ActiveItemIndex)" Value="@value" Clicked="@OnDropdownItemClicked">@text</DropdownItem>
            }
        }
    </DropdownMenu>
</Dropdown>
